package com.lanou3g.musicenjoy.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;

import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.entity.Song;
import com.lanou3g.musicenjoy.eventbus.MyEvent;

import com.lanou3g.musicenjoy.volley.VolleySingleton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/30.
 * 服务  音乐播放
 */
public class OnlineService extends Service {
    private MediaPlayer mediaPlayer;
    private List<PlayMusicEntity> entity;
    private String url;
    private int currentSong = 0;
    private RequestQueue requestQueue;
    private List<Song> datas;
    private int mode;

    @Override
    public void onCreate() {
        super.onCreate();
        //订阅
        EventBus.getDefault().register(this);
        mediaPlayer = new MediaPlayer();
        entity = new ArrayList<>();
        requestQueue = VolleySingleton.getInstance(this).getRequestQueue();
        AutoPlay();
        seekCompete();
        Log.i("syso", "进入服务的onCreate方法");
        datas=new ArrayList<>();

    }

    //当播放完成时自动播放下一曲
    public void AutoPlay() {
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.i("syso", "进入监听状态");
                if (entity.size() > 0) {
                    switch (mode) {
                        case 0://顺序
                            if (currentSong == entity.size() - 1) {
                                //当播放到最后一首时,向activity发送消息
                                EventBus.getDefault().post(new MyEvent.IsFinish(true));
                                Log.i("syso", "顺序播放完成");
                                mediaPlayer.stop();
                            } else {
                                currentSong++;
                                Log.i("syso", "顺序播放");
                                setData();
                                EventBus.getDefault().post(new MyEvent.AutoNext(true));
                            }

                            break;
                        case 1://单曲
                            setData();
                            EventBus.getDefault().post(new MyEvent.AutoNext(true));
                            break;
                        case 2://循环
                            if (currentSong == entity.size() - 1) {
                                currentSong = 0;
                            } else {
                                currentSong++;
                            }
                            setData();
                            EventBus.getDefault().post(new MyEvent.AutoNext(true));
                            break;
                        case 3://随机
                            currentSong = new Random().nextInt(entity.size());
                            Log.i("随机数", currentSong + "");
                            setData();
                            EventBus.getDefault().post(new MyEvent.AutoNext(true));
                            break;

                    }

                }


            }
        });
    }

    //当快进, 快退时会回调的方法
    public void seekCompete() {
        mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(MediaPlayer mp) {
                mp.start();
            }
        });
    }


    /**
     * 当PlayerActivity启动时通知Service,Service将数据传递给PlayerActivity
     *
     * @param event
     */
    public void onEvent(MyEvent.isStart event) {
        Log.i("xxx", "接收到通知");
        if (event.isStart() == true) {
            if (mediaPlayer.isPlaying()) {
                //发布
                //EventBus.getDefault().post(new MyEvent.getServiceData(entity, true, currentSong));
                EventBus.getDefault().post(new MyEvent.Isplay(true));
                //将数据传递给播放列表
                EventBus.getDefault().post(new MyEvent.PlayMenu(currentSong,entity));
                Log.i("ligola",currentSong+"");
                Log.i("isStart", entity.get(currentSong).getSingerName());
                Log.i("xxx", "向activity传递数据");
            }

        }
    }

    //接受activity传递过来的当前状态
    public void onEvent(MyEvent.RecycleMode recycleMode) {
        mode = recycleMode.getMode();
        Log.i("xxx", "当前循环模式 = " + mode);
    }
//    //向播放列表中传递数据
//    public void onEvent(MyEvent.PlayMenu playMenu){
//        datas= (List<Song>) playMenu.getSongMenu();
//        Log.i("fjafjfhfj",datas+"falkj");
//        EventBus.getDefault().post(new MyEvent.PlayMenu(datas));
//    }

    //从歌曲列表页面传递过来数值
    public void onEvent(MyEvent.PassData event) {

        currentSong = event.getPosition();

        this.entity = (List<PlayMusicEntity>) event.getData();
        Log.i("xxx", currentSong + "========");
        url = entity.get(currentSong).getUrl();

        Log.i("aaa", "当前的position" + currentSong);

        setData();
        Log.i("aaa", url);
        Log.i("aaa", entity.get(currentSong).getSingerName());

        //将数据传递给activity
        EventBus.getDefault().post(new MyEvent.Isplay(true));
      //  EventBus.getDefault().post(new MyEvent.getServiceData(entity, true, currentSong));

        Log.i("XXX", entity + "");
    }

    //设置数据
    private void setData() {
        if (entity.get(currentSong).getUrl() != null && entity.get(currentSong).getUrl().length() > 0) {
            url = entity.get(currentSong).getUrl();
            Log.i("wwwww", url + "0000");
            mediaPlayer.reset();
            try {
                mediaPlayer.setDataSource(url);
                Log.i("bbbbbb", "开始准备");
               // mediaPlayer.prepareAsync();
                mediaPlayer.prepare();
                Log.i("bbbbbb", "准备完成");
                mediaPlayer.start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MediaBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    public class MediaBinder extends Binder {


        //暂停以后播放
        public void start() {
            mediaPlayer.start();
        }

        //返回当前position的歌曲名
        public String getSongName() {
            return entity != null && entity.size() > 0 ? entity.get(currentSong).getSongName() : null;
        }

        //返回当前position的歌手名
        public String getSingerName() {
            return entity != null && entity.size() > 0 ? entity.get(currentSong).getSingerName() : null;
        }

        //返回当前position的图片
        public String getPicture() {
            return entity != null && entity.size() > 0 ? entity.get(currentSong).getPicUrl() : null;
        }

        //返回当前的position
        public int getPosition() {
            Log.i("xxx", currentSong + "-------");
            return currentSong;
        }

        //暂停播放
        public void pause() {
            mediaPlayer.pause();
        }

        //停止播放
        public void stop() {
            mediaPlayer.stop();
        }

        //判断当前是否正在播放
        public boolean isPlaying() {
            return mediaPlayer.isPlaying();
        }

        //拖动到指定位置
        public void seekTo(int index) {
            mediaPlayer.seekTo(index);
        }

        //下一首
        public void nextSong() {
            if (entity.size() > 0) {
                switch (mode) {
                    case 0://顺序


                    case 1://单曲
                        if (currentSong == entity.size() - 1) {
                            //当播放到最后一首时,向activity发送消息
                            Toast.makeText(OnlineService.this, "已是最后一曲", Toast.LENGTH_SHORT).show();
                        } else {
                            currentSong++;
                            Log.i("syso", "顺序播放");
                            setData();
                        }

                        break;
                    case 2://循环
                        if (currentSong == entity.size() - 1) {
                            currentSong = 0;
                        } else {
                            currentSong++;
                        }
                        setData();

                        setData();
                        break;
                    case 3://随机
                        currentSong = new Random().nextInt(entity.size());
                        Log.i("xxx", "随机播放: 位置 = " + currentSong);
                        setData();
                        break;
                }
            } else {
                Toast.makeText(OnlineService.this, "当前无下一曲", Toast.LENGTH_SHORT).show();
            }

        }

        //上一首
        public void previousSong() {
            if (entity.size() > 0) {
                switch (mode) {
                    case 0://顺序
                    case 1://单曲
                        if (currentSong == 0) {
                            Toast.makeText(OnlineService.this, "当前无上一曲", Toast.LENGTH_SHORT).show();
                        } else {
                            currentSong--;
                            setData();
                        }
                        break;
                    case 2://循环
                        if (currentSong == 0) {
                            currentSong = entity.size() - 1;
                        } else {
                            currentSong--;
                        }
                        setData();
                        break;
                    case 3://随机
                        currentSong = new Random().nextInt(entity.size());
                        setData();
                        break;
                }
            } else {
                Toast.makeText(OnlineService.this, "当前无上一曲", Toast.LENGTH_SHORT).show();
            }
        }

        //判断当前歌曲是否播放完成
        public boolean isFinish() {
            if (getCurrentPosition() == getDuration()) {
                Log.i("完成", "当前歌曲播放完成");
                return true;
            } else {
                return false;
            }
        }

        //返回当前播放的位置
        public int getCurrentPosition() {
            return mediaPlayer.getCurrentPosition();
        }

        //返回当前音频的长度
        public int getDuration() {
            return mediaPlayer.getDuration();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    EventBus.getDefault().unregister(this);
    }
}
